package com.hot100;

import java.util.HashMap;
import java.util.Map;

public class Solution76 {
    Map<Character, Integer> mapT = new HashMap<>();
    Map<Character, Integer> mapS = new HashMap<>();

    public String minWindow(String s, String t) {
        for (int i = 0; i < t.length(); i++) {
            mapT.put(t.charAt(i), mapT.getOrDefault(t.charAt(i), 0) + 1);
        }
        int min = Integer.MAX_VALUE;
        int i = 0, j = 0;
        int start = -1;
        while (i < s.length()) {
            char cur = s.charAt(i);
            mapS.put(cur, mapS.getOrDefault(cur, 0) + 1);
            while (check() && j <= i) {
                if (i - j + 1 < min) {
                    min = i - j + 1;
                    start = j;
                }
                mapS.put(s.charAt(j), mapS.getOrDefault(s.charAt(j), 0) - 1);
                j++;
            }
            i++;
        }
        return start == -1 ? "" : s.substring(start, start + min);
    }

    public boolean check() {
        for (Map.Entry<Character, Integer> entry : mapT.entrySet()) {
            Character key = entry.getKey();
            Integer value = entry.getValue();
            if (mapS.getOrDefault(key, 0) < value) return false;
        }
        return true;
    }
}
